package com.samxcode.leetcode;

import java.util.HashMap;
import java.util.Map;


/**
 * Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from
 * 1 to 3999.
 * 
 * Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from
 * 1 to 3999.
 * 
 * @author Sam
 *
 */
public class IntegerRoman {
    public static void main(String[] args) {
        System.out.println(intToRoman(51));
        System.out.println(romanToInt("DCXXI"));
    }


    /* Given an integer, convert it to a roman numeral. */
    public static String intToRoman(int num) {
        String[] k = { "", "M", "MM", "MMM" };
        String[] h = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
        String[] d = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
        String[] u = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
        // find the index in the array with Romans
        int ki = num / 1000;
        int hi = (num % 1000) / 100;
        int di = (num % 100) / 10;
        int ui = num % 10;
        return k[ki] + h[hi] + d[di] + u[ui];
    }


    public static int romanToInt(String s) {
        int res = 0;
        Map<Character, Integer> map = new HashMap<Character, Integer>() {
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            {
                put('I', 1);
                put('V', 5);
                put('X', 10);
                put('L', 50);
                put('C', 100);
                put('D', 500);
                put('M', 1000);
            }
        };
        int pre = 0, cur = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            cur = map.get(s.charAt(i));
            res += pre > cur ? -cur : cur;
            pre = cur;
        }
        return res;
    }
}
